import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, filedialog
from database.crud import get_events, add_event, get_events_by_category, delete_event, update_event
from datetime import datetime
from gui.event_dialog import EventDialog
from gui.notification import show_notification

from utils.time_utils import format_time, calculate_reminder_time
from file_ops.export import export_events, import_events
import logging


class MainWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("Smart Scheduler")
        # 初始化状态变量
        self.status_var = tk.StringVar()
        
        # 创建状态栏
        self.status_bar = ttk.Label(
            self.root, 
            textvariable=self.status_var, 
            relief=tk.SUNKEN, 
            anchor=tk.W
        )
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 设置日志记录
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler("scheduler.log"),
                logging.StreamHandler()
            ]
        )
        logging.info("Application started")
        
        # 创建其他组件
        self.create_widgets()
        self.load_events()

    def load_events(self):
        """加载事件到界面"""
        events = get_events()
        self.tree.delete(*self.tree.get_children())
        for event in events:
            self.tree.insert("", "end", values=(
                event[0], 
                event[1], 
                format_time(event[3]),  # 事件时间
                event[5]  # 类别
            ))
        self.status_var.set(f"Loaded {len(events)} events")    
        logging.info(f"Loaded {len(events)} events from database")
        
    def create_menu(self):
        menu_bar = tk.Menu(self.root)
        
        # 文件菜单
        file_menu = tk.Menu(menu_bar, tearoff=0)
        file_menu.add_command(label="Add Event", command=self.add_event)
        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=self.root.quit)
        menu_bar.add_cascade(label="File", menu=file_menu)
        
        # 视图菜单
        view_menu = tk.Menu(menu_bar, tearoff=0)
        view_menu.add_command(label="All Events", command=lambda: self.load_events())
        view_menu.add_command(label="Work", command=lambda: self.load_events_by_category("work"))
        view_menu.add_command(label="Personal", command=lambda: self.load_events_by_category("personal"))
        view_menu.add_command(label="Health", command=lambda: self.load_events_by_category("health"))
        view_menu.add_command(label="Social", command=lambda: self.load_events_by_category("social"))
        menu_bar.add_cascade(label="View", menu=view_menu)
        
        # 工具菜单
        tools_menu = tk.Menu(menu_bar, tearoff=0)
        tools_menu.add_command(label="Export Events", command=self.export_events)
        tools_menu.add_command(label="Import Events", command=self.import_events)
        menu_bar.add_cascade(label="Tools", menu=tools_menu)
        
        self.root.config(menu=menu_bar)
    
    def create_main_frame(self):
        # 创建主框架
        self.main_frame = ttk.Frame(self.root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建日程列表框架
        self.list_frame = ttk.LabelFrame(self.main_frame, text="Upcoming Events")
        self.list_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 创建Treeview
        self.tree = ttk.Treeview(self.list_frame, columns=("id", "title", "time", "category"), show="headings")
        self.tree.heading("id", text="ID", anchor=tk.CENTER)
        self.tree.heading("title", text="Event", anchor=tk.W)
        self.tree.heading("time", text="Time", anchor=tk.CENTER)
        self.tree.heading("category", text="Category", anchor=tk.CENTER)
        
        # 设置列宽
        self.tree.column("id", width=50, anchor=tk.CENTER)
        self.tree.column("title", width=250, anchor=tk.W)
        self.tree.column("time", width=150, anchor=tk.CENTER)
        self.tree.column("category", width=100, anchor=tk.CENTER)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(self.tree, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.tree.pack(fill=tk.BOTH, expand=True)
        
        # 绑定双击事件
        self.tree.bind("<Double-1>", self.edit_event)
        
        # 操作按钮框架
        btn_frame = ttk.Frame(self.main_frame)
        btn_frame.pack(fill=tk.X, padx=5, pady=5)
        
        ttk.Button(btn_frame, text="Add Event", command=self.add_event).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="Edit Event", command=self.edit_event).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="Delete Event", command=self.delete_event).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="Refresh", command=self.load_events).pack(side=tk.LEFT, padx=5)
    
    def create_status_bar(self):
        self.status_var = tk.StringVar()
        self.status_var.set("Ready - All services running")
        status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)
    
    def load_events(self, category=None):
        # 清空Treeview
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 获取事件
        if category:
            events = get_events_by_category(category)
        else:
            events = get_events()
        
        # 插入事件
        for event in events:
            event_id, title, desc, event_time, _, _, category, recurring_type, _ = event
            # 格式化时间
            formatted_time = datetime.strptime(event_time, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M")
            
            # 添加到Treeview
            self.tree.insert("", "end", values=(
                event_id,
                title,
                formatted_time,
                category
            ))
        
        self.status_var.set(f"Loaded {len(events)} events")
    
    def load_events_by_category(self, category):
        self.load_events(category)
    
    def add_event(self):
        dialog = EventDialog(self.root)
        if dialog.result:
            event_data = dialog.result
            add_event(
                title=event_data['title'],
                description=event_data['description'],
                event_time=event_data['event_time'],
                reminder_time=event_data['reminder_time'],
                category=event_data['category'],
                recurring_type=event_data['recurring_type'],
                recurring_end_date=event_data['recurring_end_date']
            )
            self.load_events()
            self.status_var.set("Event added successfully")
    
    def edit_event(self, event=None):
        selected_item = self.tree.selection()
        if not selected_item:
            messagebox.showwarning("Warning", "Please select an event to edit")
            return
        
        event_id = self.tree.item(selected_item[0])['values'][0]
        # 获取事件详情（实际项目中应查询数据库）
        # 为简化，我们使用模拟数据
        dialog = EventDialog(self.root, event_id=event_id)
        if dialog.result:
            # 更新事件（实际项目中应调用update_event）
            self.load_events()
            self.status_var.set("Event updated successfully")
    
    def delete_event(self):
        selected_item = self.tree.selection()
        if not selected_item:
            messagebox.showwarning("Warning", "Please select an event to delete")
            return
        
        event_id = self.tree.item(selected_item[0])['values'][0]
        delete_event(event_id)
        self.load_events()
        self.status_var.set(f"Event ID {event_id} deleted")
    
    def export_events(self):
        # 实际项目中应实现导出功能
        messagebox.showinfo("Export", "Export to CSV functionality is implemented in file_ops/export.py")
    
    def import_events(self):
        # 实际项目中应实现导入功能
        messagebox.showinfo("Import", "Import from CSV functionality is implemented in file_ops/export.py")

def start_gui():
    root = tk.Tk()
    app = MainWindow(root)
    root.mainloop()